'use strict';

/**
 * @ngdoc overview
 * @name sfhtHaitaoCmsApp
 * @description
 * # sfhtHaitaoCmsApp
 *
 * Main module of the application.
 */
angular
    .module('sfhtHaitaoCmsApp', [
        'ngAnimate',
        'ngAria',
        'ngCookies',
        'ngMessages',
        'ngResource',
        'ngRoute',
        'ngSanitize',
        'ngTouch',
        'dndLists',
        'ui.bootstrap',
        'angular-underscore',
        'angular-md5',
        'angular-storage',
        'ui.ace',
        'ui.uploader',
        'angular-clipboard',
        'fullPage.js',
        'ui-notification'
    ])
    .constant('CONST_UPLOAD_LIMIT', 2*1024*1024)
    .constant('CONST_H5_URL', 'http://m.tepin.hk')
    .constant('CONST_PC_URL', 'http://www.tepin.hk')
    .constant('CONST_CMS_REQUEST_URL', 'http://cms.tepin.hk/m.cmsapi')
    .constant('CONST_CMS_REQUEST_URL_FILE', 'http://cms.tepin.hk/file.cmsapi')
    .constant('CONST_NONE_APPEND_WORD', 'sfhaitao.xyz!')
    .constant('CONST_PASSWORD_SLOT', 'www.sfht.com')
    .constant('CONST_WEB_LOGIN_LINK', 'http://cms.tepin.hk/index.html#/login')
    .constant('CONST_INDEX_LINK', 'http://cms.tepin.hk/index.html')
    .constant('CONST_DEFAULT_REQUEST_HEADER', {
        _sm: 'md5'
    })
    .constant('TOKEN_AND_SIGNATURE_ERROR_GROUP', [-360, -300, -180])
    .constant('PC_HEADER_RESOURCE_TYPE', "PC_HEADER")
    .constant('H5_HEADER_RESOURCE_TYPE', "H5_HEADER")
    .constant('HTML_MODULE_LIST', [])
    .constant('RICH_HTML_MODULE_LIST', ['richHtml', 'h5richHtml', 'h5html', 'h5coupon', 'simplehtml', 'coupon', 'h5popup', 'bottomlip', 'rightsidelip', 'leftsidelip'])
    //不允许批量修改的字段列表
    .constant('REJECT_BANTCHUPDATE_FIELDNAME', ['itemId', 'name', 'imgUrl', 'link', 'h5link', 'price', 'originPrice', 'id'])
    .config(function(storeProvider, NotificationProvider) {
        //localStorage
        storeProvider.setStore('localStorage');

        NotificationProvider.setOptions({
            delay: 3000,
            startTop: 20,
            startRight: 10,
            verticalSpacing: 20,
            horizontalSpacing: 20,
            positionX: 'left',
            positionY: 'top'
        });

    }).factory('AcitivityStore', function(store) {
        return store.getNamespacedStore('AcitivityStore');
    }).factory('PageStore', function(store) {
        return store.getNamespacedStore('PageStore');
    }).factory('Moduletore', function(store) {
        return store.getNamespacedStore('Moduletore');
    }).factory('ModuleDataStore', function(store) {
        return store.getNamespacedStore('ModuleDataStore');
    })
    // .factory('AppIndexPermission', function(store) {
    //     //判断是否具有appIndex的修改权限
    //     var profile = store.get("profile");
    //     return profile.role == "ADMIN" || _.contains(profile.permissions, "page.appindex");
    // })
    .factory('Uploader', function(CONST_CMS_REQUEST_URL_FILE, CONST_UPLOAD_LIMIT, uiUploader, store) {
        function dealUpload($scope, uploadfile, type) {
            uiUploader.startUpload({
                url: CONST_CMS_REQUEST_URL_FILE,
                concurrency: 1,
                onProgress: function(file) {
                    $scope.$apply();
                },
                onCompleted: function(file, response) {
                    $(".file-mask").css("display", "none");
                    var res = JSON.parse(response);
                    var arr = _.values(res.content[0]);
                    if (uploadfile == "backgroundUrl") {
                        $scope.page.pageConfig.backgroundUrl = arr[0];
                        $scope.page.isBackgroundUrlCompleted = true;
                    } else if (uploadfile == "shareIcon") {
                        $scope.page.pageConfig.shareIcon = arr[0];
                        $scope.page.isShareIconCompleted = true;
                    } else if (type == "modulePic") {
                        uploadfile.picUrl = arr[0];
                        uploadfile.isCompleted = true;
                    } else if (type == "moduleBackgroundUrl") {
                        //模块背景
                        $scope.moduleConfig.style ? $scope.moduleConfig.style : $scope.moduleConfig.style = {};
                        $scope.moduleConfig.style.backgroundUrl = arr[0];
                        $scope.isBackgroundUrlCompleted = true;
                    } else if (type == "moduleLogo") {
                        //模块背景
                        $scope.moduleConfig.moduleLogo = arr[0];
                        $scope.isModuleLogoCompleted = true;
                    } else if (type == "image") {
                        uploadfile.propertyValue = arr[0];
                        uploadfile.isCompleted = true;
                        var img = new Image();
                        img.src = arr[0];
                        img.onload = function() {
                            $scope.isCompleted = true;
                            //新增
                            var height = _.findWhere($scope.items, {
                                'fieldName': 'height'
                            });
                            //新增
                            var width = _.findWhere($scope.items, {
                                'fieldName': 'width'
                            });
                            if (!height) {
                                //修改
                                height = _.find($scope.items, function(item) {
                                    return item.field && item.field.fieldName == 'height';
                                });
                            }
                            if (!width) {
                                //修改
                                width = _.find($scope.items, function(item) {
                                    return item.field && item.field.fieldName == 'width';
                                });
                            }
                            if (height) {
                                height.propertyValue = img.height;
                            }
                            if (width) {
                                width.propertyValue = img.width;
                            }
                            $scope.$digest();
                        };
                    } else {
                        if (arr.length > 0) {
                            uploadfile.fileName = arr[0];
                            uploadfile.isCompleted = true;
                        }

                    }
                    $scope.$digest();
                    window.localStorage.setItem("fileName", arr[0]);
                },
                onCompletedAll: function(files) {
                    $(".file-mask").css("display", "none");
                    $('#fileuploader').off('change');
                }
            });
        }
        return {
            uploadFile: function($scope, uploadfile, type) {
                $('#fileuploader').on('change', function(e) {
                    var files = e.target.files;
                    if (files) {
                        var isBelow2M = false;
                        var isAllowFile =true;
                        _.each(files, function(file){
                            isBelow2M = isBelow2M || (file.size > CONST_UPLOAD_LIMIT);
                            isAllowFile = isAllowFile && /(.jpg|.png|.jpeg|.gif|.bmp)$/.test(file.name)
                        });
                        if (isBelow2M && !isAllowFile) {
                            return setTimeout(function() {
                                alert('文件类型不匹配并且大于2M无法上传！');
                            }, 0);
                        }else if (isBelow2M && isAllowFile) {
                            return setTimeout(function() {
                                alert('文件大于2M无法上传！');
                            }, 0);
                        }else if (!isBelow2M && !isAllowFile) {
                            return setTimeout(function() {
                                alert('文件类型不匹配无法上传！');
                            }, 0);
                        }

                        $(".file-mask").css("display", "block");
                    }
          
                    uiUploader.addFiles(e.target.files);
                    dealUpload($scope, uploadfile, type);
                });
                $('#fileuploader').trigger('click');
            }
        }

    })
    .config(function($routeProvider, $httpProvider) {
        $httpProvider.defaults.headers.post['Content-Type'] = "application/x-www-form-urlencoded; charset=UTF-8";
        $routeProvider
            .when('/', {
                templateUrl: 'views/main.html',
                controller: 'MainCtrl'
            })
            .when('/login', {
                templateUrl: 'views/login.html',
                controller: 'LoginCtrl'
            })
            .when('/about', {
                templateUrl: 'views/about.html',
                controller: 'AboutCtrl'
            })
            .when('/page/manager', {
                templateUrl: 'views/page/page.manager.html',
                controller: 'PageManagerCtrl'
            })
            .when('/page/edit/:pageid', {
                templateUrl: 'views/page/page.edit.html',
                controller: 'PageEditCtrl'
            })
            .when('/activitypage/manager', {
                templateUrl: 'views/activitypage/activitypage.manager.html',
                controller: 'ActivityPageManagerCtrl'
            })
            //定制
            .when('/module/html/:pageType/:moduleName/:fn/:pageid/:placeholder', {
                templateUrl: 'views/module/module.html.html',
                controller: 'ModuleHtmlCtrl'
            })
            .when('/module/richhtml/:pageType/:moduleName/:fn/:pageid/:placeholder', {
                templateUrl: 'views/module/module.richhtml.html',
                controller: 'ModuleRichHtmlCtrl'
            })
            .when('/module/common/:pageType/:moduleName/:fn/:pageid/:placeholder', {
                templateUrl: 'views/module/module.common.html',
                controller: 'ModuleCommonCtrl'
            })
            .when('/page/headerconfig', {
                templateUrl: 'views/page/header.config.html',
                controller: 'ModuleHeaderConfigCtrl'
            })
            .when('/module/manager', {
                templateUrl: 'views/module/module.manager.html',
                controller: 'ModuleManageCtrl'
            })
            .when('/module/manager/:id', {
                templateUrl: 'views/module/module.edit.html',
                controller: 'ModuleEditCtrl'
            })
            .when('/resource/manager', {
                templateUrl: 'views/resource/resource.manager.html',
                controller: 'ResourceCtrl'
            })
    });
